<template>
  <el-container>
    <el-main height="">
      <!-- 购物车表格上方添加地址选择 -->
      <el-row :gutter="20" style="margin-bottom: 20px">
        <el-col :span="3" :offset="0"></el-col>
        <el-col :span="18" :offset="0">
          <el-card>
            <div style="display: flex; align-items: center; gap: 20px">
              <span style="font-weight: bold">配送地址：</span>
              <el-select
                v-model="address"
                placeholder="请选择收货地址"
              >
                <el-option
                  v-for="item in addressList"
                  :key="item"
                  :label="item.address"
                  :value="item.id"
                >
                  <div style="display: flex; justify-content: space-between">
                    <span>{{ item.address }}</span>
                    <span style="color: #999">{{ item.username }} {{ item.phoneNumber }}</span>
                  </div>
                </el-option>
              </el-select>
            </div>
          </el-card>
        </el-col>
        <el-col :span="3" :offset="0"></el-col>
      </el-row>
      <el-row :gutter="20">
          <el-col :span="3" :offset="0"></el-col>
          <el-col :span="18" :offset="0">
            <el-card>
              <el-table :data="tableData" style="width: 100%">
                  <el-table-column prop="name" label="商品名称" width="240" ></el-table-column>
                  <el-table-column prop="description" label="商品描述" width="240"></el-table-column>
                  <el-table-column prop="price" label="商品价格" width="240"></el-table-column>
                  <el-table-column prop="amount" label="商品数量" width="240">
                    <template #default="scope">
                      <el-input-number v-model="scope.row.amount" :min="1" :max="1000"></el-input-number>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="100">
                      <template #default="scope">
                          <el-button type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
                      </template>
                  </el-table-column>
              </el-table>
            </el-card>
          </el-col>
          <el-col :span="3" :offset="0"></el-col>
      </el-row>
    </el-main>
    <el-footer style="height: auto; position: fixed; bottom: 0; left: 0; right: 0; background: white; box-shadow: 0 -2px 10px rgba(0,0,0,0.1)">
      <div style="max-width: 1200px; margin: 0 auto; padding: 20px;">
        <el-row type="flex" justify="space-between" align="middle">
          <el-col :span="12">
            <div style="font-size: 24px; color: #ff4400">
              合计：<span style="font-weight: bold">¥{{ totalAmount.toFixed(2) }}</span>
            </div>
          </el-col>
          <el-col :span="12" style="text-align: right">
            <el-button
              type="danger"
              style="padding: 15px 40px; font-size: 18px"
              @click="handleCheckout"
            >
              立即结算（{{ totalCount }}件）
            </el-button>
          </el-col>
        </el-row>
      </div>
    </el-footer>
  </el-container>
</template>
<script setup>
import axios from 'axios';
import { onMounted, ref } from 'vue';
import { ElMessage,ElMessageBox } from 'element-plus'
// 在原有 script 中添加计算属性
import { computed } from 'vue'
import qs from 'qs'

// 购物车地址选择
const addressList = ref([])
const address = ref(null)

// 获取购物车数据
//购物车数据数组
const tableData =ref([])
//获取用户信息
const user = JSON.parse(localStorage.getItem('user'))
//查询购物车
const getCart = () => {
  let id = user.id
  axios.get(BASE_URL+'/v1/cart/list/'+id).then(res => {
    if (res.data.code === 2000) {
      tableData.value = res.data.data
      console.log(tableData.value)
    } else {
      ElMessage.error(res.data.msg)
    }
  })
}

//
onMounted(() => {
  getCart()
  getAddress()
})

//查询地址
const getAddress = () => {
  axios.get(BASE_URL+'/v1/address/address/'+user.id).then(res => {
    if (res.data.code === 2000) {
      addressList.value = res.data.data
      console.log(addressList.value)
    } else {
      ElMessage.error(res.data.msg)
    }
 })
}




// 计算总金额
const totalAmount = computed(() => {
  return tableData.value.reduce((sum, item) => {
    return sum + (parseFloat(item.price) * item.amount)
  }, 0)
  orderData.value.total = totalAmount.value.toFixed(2)
})

// 计算总数量
const totalCount = computed(() => {
  return tableData.value.reduce((sum, item) => sum + item.amount, 0)
})
//提交给订单的数据
var orderData = ref({
  userId:user.id,
  addressId:null,
  total:null
})
// 结算处理函数
const handleCheckout = () => {
  ElMessageBox.confirm(`确认结算 ¥${totalAmount.value.toFixed(2)} 吗？`, '确认订单', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    if(!address.value){
      ElMessage.error('请选择收货地址!');
      return;
    }
    //先把购物车数据更新到数据库中
    axios.post(BASE_URL+'/v1/cart/update',tableData.value).then(res => {
      if (res.data.code === 2000) {
        ElMessage.success('购物车数据已更新!');
        orderData.value.total = totalAmount.value.toFixed(2)
        orderData.value.addressId = address.value
        let data = qs.stringify(orderData.value)
        console.log(data)
        // 这里添加结算逻辑
        axios.post(BASE_URL+'/v1/order/create',data).then(res => {
          if (res.data.code === 2000) {
            ElMessage.success('订单创建成功!');
            getCart()
            getAddress()
          }else {
            ElMessage.error(res.data.msg)
          }
        })
      }else {
        ElMessage.error(res.data.msg)
      }
    })
  })
}
//定义删除商品的方法
const handleDelete = (id) =>{
  axios.post(BASE_URL+'/v1/cart/delete/'+id).then(response => {
    if (response.data.code === 2000) {
      ElMessage.success('删除成功!');
      getCart();
    } else {
      ElMessage.error(response.data.msg);
    }
  })
}
</script>


<style scoped>
/* 添加样式确保底部栏层级 */
.el-footer {
  z-index: 1000;
}
</style>
